<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/11/29
 * Time: 11:14
 */
namespace App\Http\Controllers\Api\V2;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Http\Controllers\Controller;
use App\Modules\EntBookInfo;
use App\Modules\EntBookImg;
use App\Modules\EntMemberInfo;
use App\Modules\EntBookSumUp;
use App\Modules\EntBookCollect;
use App\Modules\EntBookViewLog;
use Validator, DB;

use App\Models\BookModel;

class BookController extends BaseController
{
    protected $url;
    public function __construct(){
        $this->url = env('ADMIN_HOST');
    }

    /**
     * 书籍分类
     *
     */
    public function getBookType()
    {
        $bookModel  = new BookModel();
        $bookTypes  = $bookModel->get_book_types();
        $data = ['message' => 'ok', 'code' => '200', 'booktypelist' => $bookTypes];
        return response()->json($data);
    }





    /**
     * 广告
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBookHotsList()
    {
        $bookModel  = new BookModel();
        $hotBooks   = $bookModel->get_hot_books();
        return response()->json(['message' => 'ok', 'code' => '200', 'hotslist' => $hotBooks]);
    }


    /**
     * 推荐书籍
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBookRecommendList()
    {
        $bookModel  = new BookModel();
        $recommentBooks = $bookModel->get_recomment_books();
        return response()->json(['message' => 'ok', 'code' => '200', 'bookrecommendlist' => $recommentBooks]);
    }




    /**
     * 添加读书改进计划
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bookSumUpStore(Request $request)
    {
        $result = 'no';
        $rules = [
            'mobile' => 'required',
            'id' => 'required',
            'key' => 'required',
            'upid' => 'required',
            'timestamp' => 'required',
            'sign' => 'required'
        ];
        $messages = [
            'mobile.required' => '2019',
            'id.required' => '2020',
            'key.required' => '2021',
            'upid.required' => '2036',
            'timestamp.required' => '2026',
            'sign.required' => '2027'
        ];
        $mobile = $request->input('mobile');
        $key = $request->input('key');
        $id = $request->input('id');
        $upid = $request->input('upid');
        $bookidea1 = $request->input('bookidea1');
        $bookidea2 = $request->input('bookidea2');
        $bookidea3 = $request->input('bookidea3');
        $bookidea4 = $request->input('bookidea4');
        $timestamp = $request->input('timestamp');
        $sign = $request->input('sign');

        $params = [
            'mobile'    => $mobile,
            'key'       => $key,
            'id'        => $id,
            'upid'      => $upid,
            'bookidea1' => $bookidea1,
            'bookidea2' => $bookidea2,
            'bookidea3' => $bookidea3,
            'bookidea4' => $bookidea4,
            'timestamp' => $timestamp,
            'sign' => $sign
        ];
        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        if ($this->checkSign($params) == true) {

            $memNumber = $this->memNumber($mobile, $key);

            if (count($memNumber) > 0) {
                if ($upid == 0) {
                    //验证是否已经添加过
                    $entBookSumUp = new EntBookSumUp();
                    $entBookSumUp->BookID = $id;
                    $entBookSumUp->MemNumber = $memNumber->MemNumber;
                    $entBookSumUp->BookReview1 = $bookidea1;
                    $entBookSumUp->BookReview2 = $bookidea2;
                    $entBookSumUp->BookReview3 = $bookidea3;
                    $entBookSumUp->BookReview4 = $bookidea4;
                    $entBookSumUp->AddDate = date('Y-m-d H:i:s', time());
                    $entBookSumUp->save();
                } else {
                    //验证是否已经添加过
                    $entBookSumUp = EntBookSumUp::find($upid);
                    $entBookSumUp->BookReview1 = $bookidea1;
                    $entBookSumUp->BookReview2 = $bookidea2;
                    $entBookSumUp->BookReview3 = $bookidea3;
                    $entBookSumUp->BookReview4 = $bookidea4;
                    $entBookSumUp->AddDate = date('Y-m-d H:i:s', time());
                    $entBookSumUp->save();
                }
                if ($entBookSumUp) {
                    return response()->json(['message' => 'ok', 'code' => '200']);
                } else {
                    return response()->json(['message' => $result, 'code' => '3021']);
                }
            } else {
                return response()->json(['message' => $result, 'code' => '3020']);
            }
        } else {
            return response()->json(['message' => $result, 'code' => '3019']);
        }
    }

    /**
     * 收藏书籍
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bookCollectStore(Request $request)
    {
        $result = 'no';
        $rules = [
            'mobile' => 'required',
            'id' => 'required',
            'key' => 'required',
            'timestamp' => 'required',
            'sign' => 'required'
        ];
        $messages = [
            'mobile.required' => '2031',
            'id.required' => '2032',
            'key.required' => '2033',
            'timestamp.required' => '2034',
            'sign.required' => '2035'
        ];
        $mobile = $request->input('mobile');
        $key = $request->input('key');
        $id = $request->input('id');
        $timestamp = $request->input('timestamp');
        $sign = $request->input('sign');
        $params = ['mobile' => $mobile, 'key' => $key, 'id' => $id, 'timestamp' => $timestamp, 'sign' => $sign];
        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        if ($this->checkSign($params) == true) {
            $memNumber = $this->memNumber($mobile, $key);
            if (count($memNumber) > 0) {
                $entBookInfo = EntBookInfo::select('FilePath1')->where('BookID', $id)->where('DeleteMark', '1')->first();
                if (count($entBookInfo) > 0) {
                    $entBookCollect = EntBookCollect::select('ColID')->where('MemNumber', $memNumber->MemNumber)->where('BookID', $id)->first();
                    if (count($entBookCollect) == 0) {
                        $BookCollectStore = new EntBookCollect();
                        $BookCollectStore->BookID = $id;
                        $BookCollectStore->MemNumber = $memNumber->MemNumber;
                        $BookCollectStore->FilePath1 = $entBookInfo->FilePath1;
                        $BookCollectStore->AddDate = date('Y-m-d H:i:s', time());
                        $BookCollectStore->save();
                        if ($BookCollectStore) {
                            return response()->json(['message' => 'ok', 'code' => '200']);
                        } else {
                            return response()->json(['message' => $result, 'code' => '3022']);
                        }
                    } else {
                        EntBookCollect::destroy($entBookCollect->ColID);
                        return response()->json(['message' => 'ok', 'code' => '200']);
                    }
                } else {
                    return response()->json(['message' => $result, 'code' => '3024']);
                }
            } else {
                return response()->json(['message' => $result, 'code' => '3025']);
            }
        } else {
            return response()->json(['message' => $result, 'code' => '3026']);
        }
    }

    /**
     * 返回会员标示
     * @param string $mobile
     * @param string $appkey
     * @return mixed
     */
    protected function memNumber($mobile = '', $appkey = '')
    {
        $entBookInfo = EntMemberInfo::select('MemNumber', 'MemEndTime', 'States')
            ->where('DeleteMark', '1')
            ->where('AppKey', $appkey)
            ->where('UserName', $mobile)
            ->first();
        return $entBookInfo;
    }



    /**========Ron重新编码==========*/


    /**
     * 书籍详细
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getbookdetail(Request $request)
    {
        $result = "no";
        try {
            $rules = [
                'id' => 'required',
            ];
            $messages = [
                'id.required' => '2029',
            ];
            
            $id     = $request->input('id');
            $mobile = $request->input('mobile', 0);
            
            $key    = $request->input('key', 0);
            if($mobile && $key) {
                $params = ['mobile' => $mobile, 'key' => $key, 'id' => $id];
                $v = Validator::make($params, $rules, $messages);
                if ($v->fails()) {
                    return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
                }
                //获取书籍详细
                $entBookInfo = EntBookInfo::findOrFail($id);
                if (count($entBookInfo) > 0) {
                    $entBookInfo->FilePath1 = $this->url . $entBookInfo->FilePath1;
                }
                //获取PPT
            
                $entBookImg = EntBookImg::select('FilePath1', 'SortNumber')
                    ->where('BookID', $id)
                    ->orderBy('SortNumber', 'asc')
                    ->orderBy('AddDate', 'asc')
                    ->get();

                if (count($entBookImg) > 0) {
                    foreach ($entBookImg as $imgkey) {
                        $imgkey->FilePath1 = $this->url . $imgkey->FilePath1;
                    }
                }
                //更新书籍查看数
                
                DB::table('BookInfo')
                    ->where('BookID', $entBookInfo->BookID)
                    ->update(['ReadNumber' => $entBookInfo->ReadNumber + 1]);

                //书籍读书改进计划
                $memNumber = $this->memNumber($mobile, $key);

                if (count($memNumber) > 0) {
                    //会员是否到期
                    $nowtime = date('Y-m-d h:i:s', time());
                    $endtime = $memNumber->MemEndTime;
                    if (strtotime($nowtime) > strtotime($endtime)) {
                        $i = 1;//会员到期
                    } else {
                        $i = 2; //已付费
                    }
                    //书籍收藏 0--未收藏 1--已收藏
                    $isCollect = '0';
                    $entBookCollect = EntBookCollect::select('ColID')->where('MemNumber', $memNumber->MemNumber)->where('BookID', $id)->get();
                    if (count($entBookCollect) > 0) {
                        $isCollect = '1';
                    }

                    //改进计划
                    $entBookSumUp = EntBookSumUp::select('SumUpID', 'BookReview1', 'BookReview2', 'BookReview3', 'BookReview4')
                        ->where('BookID', $id)
                        ->where('MemNumber', $memNumber->MemNumber)
                        ->orderBy('SumUpID','desc')
                        ->first();
                    if (count($entBookSumUp) == 0) {
                        $entBookSumUp = ['SumUpID' => '0', 'BookReview1' => '', 'BookReview2' => '', 'BookReview3' => '', 'BookReview4' => ''];
                    }

                    //观看记录
                    $checkBookViewLog = EntBookViewLog::select('ViewLogID')
                        ->where('BookID', $id)
                        ->where('MemNumber', $memNumber->MemNumber)
                        ->get();

                    if (count($checkBookViewLog) == 0) {
                        $entBookViewLog = new EntBookViewLog();
                        $entBookViewLog->BookID = $id;
                        $entBookViewLog->MemNumber = $memNumber->MemNumber;
                        $entBookViewLog->FilePath1 = $entBookInfo->FilePath1;
                        $entBookViewLog->StartTime = date('Y-m-d H:i:s', time());
                        $entBookViewLog->EndTime = '';
                        $entBookViewLog->AddDate = date('Y-m-d H:i:s', time());
                        $entBookViewLog->save();
                    }

                    $data['error_code'] = '200';
                    $data['error_info'] = '成功';
                    $data['data']['bookdetail'] = $entBookInfo;
                    $data['data']['bookdetail']['isCollect'] = $isCollect;
                    $data['data']['imglist'] = $entBookImg;
                    $data['data']['sumuplist'] = $entBookSumUp;
                    $data['data']['isCollect'] = $isCollect;

                    if ($memNumber->States == 1) {
                        $nowtime = date('Y-m-d h:i:s', time());
                        $endtime = $memNumber->MemEndTime;
                        if (strtotime($nowtime) > strtotime($endtime)) {
                            $memstate = 1;//会员到期
                        } else {
                            $memstate = 2; //已付费
                        }
                    } else {
                        $memstate = 4;//未付费
                    }

                    $data['data']['memstate'] = $memstate;
                } else {
                    throw new \Exception("用户不存在", '400');
                }
            } else {
                //获取书籍详细
                $entBookInfo = EntBookInfo::findOrFail($id);
                if (count($entBookInfo) > 0) {
                    $entBookInfo->FilePath1 = $this->url . $entBookInfo->FilePath1;
                }
                //获取PPT
                
                $entBookImg = EntBookImg::select('FilePath1', 'SortNumber')
                    ->where('BookID', $id)
                    ->orderBy('SortNumber', 'asc')
                    ->orderBy('AddDate', 'asc')
                    ->get();

                if (count($entBookImg) > 0) {
                    foreach ($entBookImg as $imgkey) {
                        $imgkey->FilePath1 = $this->url . $imgkey->FilePath1;
                    }
                }
                //更新书籍查看数
                
                DB::table('BookInfo')
                    ->where('BookID', $entBookInfo->BookID)
                    ->update(['ReadNumber' => $entBookInfo->ReadNumber + 1]);

                $data['error_code'] = '200';
                $data['error_info'] = '成功';
                $data['data']['bookdetail'] = $entBookInfo;
                $data['data']['bookdetail']['isCollect'] = '';
                $data['data']['imglist'] = $entBookImg;
                $data['data']['sumuplist'] = '';
                $data['data']['isCollect'] = '';
                $data['data']['memstate'] = 3;
            }
            
        } catch (\Exception $e) {
            $data['error_code'] = $e->getCode();
            $data['error_info'] = $e->getMessage();
            $data['data'] = '';
        }

        return $data;
    }

    /**
     * 所有书籍
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBookList(Request $request)
    {
        $mobile = $request->input('mobile', 0);
        $key    = $request->input('key', 0);
        $date   = date('Y-m-d',time());


        //读取所有书籍
        $entBookInfo = DB::table('VW_WEB_BookInfo')
            ->select('BookID', 'IsGratis', 'BookTitle', 'BookDesc', 'FilePath1', 'IsShow', 'DeleteMark', 'ReleaseDate', 'AddDate','publish_date')
            ->where('IsShow', 1)
            ->where('DeleteMark', 1)
		->where('publish_date','<=',date('Y-m-d',time()))
            ->orderBy('SortNumber', 'asc')
            ->orderBy('AddDate', 'desc')
            ->get();

       /* $SQL = "SELECT BookID, IsGratis, BookTitle, BookDesc, FilePath1, IsShow, DeleteMark, ReleaseDate, AddDate
                  FROM VW_WEB_BookInfo
                 WHERE IsShow = 1
                   AND DeleteMark = 1
                   AND publish_date <= '{$date}'
              ORDER BY SortNumber,AddDate desc
                   ";
        $entBookInfo = DB::select($SQL);*/

	$nowtime = time();
        foreach ($entBookInfo as $book) {
            $book->FilePath1 = $this->url . $book->FilePath1;
            $book->hasReadPlan = 0;
        }

        define('mem_status_unlogin',3);
        define('mem_status_had_end',1);
        define('mem_status_payed',2);
        define('mem_status_unpay',4);
        $memStatus = mem_status_unlogin;

        
        $entMemberInfo = false;
        if($mobile && $key){
            $entMemberInfo = $this->memNumber($mobile, $key);
            $entMemberInfo = $entMemberInfo?$entMemberInfo:false;
        }

        if($entMemberInfo) {
            $memTime    = $entMemberInfo->AddDate;
            $memNumber  = $entMemberInfo->MemNumber;

            //取出该会员所有收藏的书籍
            $collectList = EntBookCollect::where('MemNumber', $memNumber)->distinct()->pluck('BookID')->toArray();
            $colllist    = $collectList?$collectList:[];

            //取出已经填写过读书计划的书籍
            $hasWriteReadPlan = DB::table('booksumup')->where('MemNumber',$memNumber)->distinct()->pluck('BookID')->toArray();
            $hasWriteReadPlan = $hasWriteReadPlan?$hasWriteReadPlan:[];

            //程序调整书籍排列顺序0不显示 1显示
            foreach ($entBookInfo as $book) {
                $bookAddTime    = $book->AddDate;
                $memberAddTime  = $memTime;
                if (strtotime($bookAddTime) > strtotime($memberAddTime)) {
                    $book->IsShow = 0;
                }

                //是否收藏过该书籍 0-否 1-是--MasterID
                $bookId = $book->BookID;
                $book->MasterID     = in_array($bookId, $colllist)?1:0;
                $book->hasReadPlan  = in_array($bookId, $hasWriteReadPlan)?1:0;
            }


            //判断用户的状态
            if ($entMemberInfo->States == 1) {
                $nowtime = date('Y-m-d h:i:s', time());
                $endtime = $entMemberInfo->MemEndTime;
                if (strtotime($nowtime) > strtotime($endtime)) {
                    $memStatus = mem_status_had_end;//会员到期
                } else {
                 
                    $memStatus = mem_status_payed; //已付费
                }
            } else {
                $memStatus = mem_status_unpay;//未付费
            }
        }

        $data['error_code'] = '200';
        $data['error_info'] = '成功';
        $data['data']       = [
            'booklist'  => $entBookInfo,
            'memstate'  => $memStatus
        ];
        return $data;
    }







}
